import typing as t

from scapy.layers.http import *
from scapy.layers.inet import *
from scapy.layers.tls.all import *

from app.proto import PacketRecord, HTTPPacketRecord, TLSPacketRecord


def parse_packet(packet: Packet) -> t.Tuple[str, t.Optional[PacketRecord]]:
    if packet.haslayer(TCP):
        src_port = packet[TCP].sport
        dest_port = packet[TCP].dport

        # 只保留走80端口的HTTP Request
        try:
            if packet.haslayer(HTTP) and (src_port == 80 or dest_port == 80) and isinstance(packet[HTTP].payload, HTTPRequest):
                # print("HTTP")
                return "http", HTTPPacketRecord(packet)
            elif packet.haslayer(TLS) and (src_port == 443 or dest_port == 443) and packet.haslayer(TLSClientHello):
                # print("TLS")
                return "tls", TLSPacketRecord(packet)
        except ValueError:
            pass
    return "raw", PacketRecord(packet)
